package com.hjq.fcloud.other

import android.app.Activity
import android.text.TextUtils
import android.view.View
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout
import com.hjq.base.BaseActivity
import com.hjq.fcloud.R
import com.hjq.fcloud.app.AppActivity
import com.hjq.fcloud.bean.CommonFileBean
import com.hjq.fcloud.bean.FileItemBean
import com.hjq.fcloud.glide.Glide4Engine
import com.hjq.fcloud.ui.activity.CameraActivity
import com.hjq.fcloud.ui.activity.VideoPlayerActivity
import com.hjq.fcloud.ui.activity.VideoSelectActivity
import com.hjq.fcloud.utils.CommonUploadUtils
import com.hjq.fcloud.utils.VideoThumbnailUtil
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.toast.ToastUtils
import com.zhongjh.albumcamerarecorder.listener.OnResultCallbackListener
import com.zhongjh.albumcamerarecorder.settings.CameraSetting
import com.zhongjh.albumcamerarecorder.settings.GlobalSetting
import com.zhongjh.albumcamerarecorder.settings.MultiMediaSetting.Companion.from
import com.zhongjh.common.entity.LocalFile
import com.zhongjh.common.entity.MultiMedia
import com.zhongjh.common.entity.SaveStrategy
import com.zhongjh.common.enums.MimeType.Companion.ofAll
import com.zhongjh.common.enums.MimeType.Companion.ofVideo
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.File


/**
 * 公共视频选择处理
 */
class SelectedVideoHelper {

    companion object {

        /**
         * 视频预览
         */
        private fun jumpVideoPreview(
            mActivity: Activity, url: String
        ) {

//            //网络视频用浏览器打开，本地视频直接播放
//            if(url.contains("http")){
//                FileOpenUtils.openBySystem(mActivity, url)
//            }else{
//                VideoPlayerActivity.Companion.start(mActivity, url)
//            }

//            VideoPlayActivity.Builder()
//                .setVideoTitle("视频播放")
//                .setVideoSource(url)
//                .setAutoOver(false)
//                .setActivityOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
//                .start(mActivity)

            VideoPlayerActivity.Companion.start(mActivity, url)
        }
    }


    //九宫格view
    private var mSelectedImageView: BGASortableNinePhotoLayout? = null
    private var mActivity: AppActivity? = null

    //上传成功的文件列表
    private var uploadSuccessList = ArrayList<CommonFileBean>()

    /**
     * RecycleView中存在BGASortableNinePhotoLayout复用问题，所以每次获取和添加都重新创建对象，要不然滑动会影响展示
     */
    fun getData():ArrayList<CommonFileBean>{
        var retList = ArrayList<CommonFileBean>()
        uploadSuccessList.forEach {
            retList.add(it)
        }
        return retList
    }

    /**
     * RecycleView中存在BGASortableNinePhotoLayout复用问题，所以每次获取和添加都重新创建对象，要不然滑动会影响展示
     */
    fun setData(data: ArrayList<FileItemBean>? = null){
        uploadSuccessList.clear()
        var realData = ArrayList<String>()
        data?.forEach {
            var isVideo = (!TextUtils.isEmpty(it.url2))
            var commonFileBean = CommonFileBean()
            if(isVideo){
                commonFileBean.url = it.url
                commonFileBean.videoThumbnailUrl = it.url2
                realData.add(it.url2)
            }else{
                commonFileBean.url = it.url
                realData.add(it.url)
            }
            uploadSuccessList.add(commonFileBean)
        }
        mSelectedImageView?.data  = realData
    }

    /**
     * 初始化选择控件
     */
    fun initSelectedVideoView(
        activity: AppActivity, selectedView: BGASortableNinePhotoLayout, selectCount: Int = 5
    ) {
        this.mSelectedImageView = selectedView
        this.mActivity = activity

        selectedView.maxItemCount = selectCount
        selectedView.setDeleteDrawableResId(R.drawable.photo_delete)
        selectedView.setPlusDrawableResId(R.drawable.img_camera)
        selectedView.setDelegate(object : BGASortableNinePhotoLayout.Delegate {
            override fun onClickAddNinePhotoItem(
                sortableNinePhotoLayout: BGASortableNinePhotoLayout,
                view: View,
                position: Int,
                models: ArrayList<String>
            ) {
                choiceVideoWrapper()
            }

            override fun onClickDeleteNinePhotoItem(
                sortableNinePhotoLayout: BGASortableNinePhotoLayout,
                view: View,
                position: Int,
                model: String,
                models: ArrayList<String>
            ) {
                uploadSuccessList.removeAt(position)
                selectedView.removeItem(position)
            }

            override fun onClickNinePhotoItem(
                sortableNinePhotoLayout: BGASortableNinePhotoLayout,
                view: View,
                position: Int,
                model: String,
                models: ArrayList<String>
            ) {
                jumpVideoPreview(activity, uploadSuccessList.get(position).url)
            }

            override fun onNinePhotoItemExchanged(
                sortableNinePhotoLayout: BGASortableNinePhotoLayout,
                fromPosition: Int,
                toPosition: Int,
                models: ArrayList<String>
            ) {
            }
        })
    }

    /**
     * 视频选择
     */
    private fun choiceVideoWrapper() {
        mActivity?.let { mActivity ->
            XXPermissions.with(mActivity).permission(
                Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.CAMERA
            ).request(object : PermissionCallback() {
                override fun onGranted(permissions: List<String>, all: Boolean) {
//                        jumpSystemVideoRecord(mActivity)
                    jumpCustomVideoRecord(mActivity)
                }
            })
        }
    }

    /**
     * 跳转自定义视频录制
     */
    private fun jumpCustomVideoRecord(mActivity: BaseActivity) {
        //最大录制时间
        val MAX_RECORD_DURATION = 60
        // 拍摄有关设置
        val cameraSetting = CameraSetting()
        // 支持的类型：图片，视频
        cameraSetting.mimeTypeSet(ofVideo())
        cameraSetting.duration(MAX_RECORD_DURATION)
        // 全局
        val globalSetting: GlobalSetting = from(mActivity).choose(ofAll())
        globalSetting.cameraSetting(cameraSetting)
        globalSetting // 设置路径和7.0保护路径等等
            .allStrategy(
                SaveStrategy(
                    true, AppConfig.getPackageName() + ".provider", "fcloud"
                )
            ) // for glide-V4
            .imageEngine(Glide4Engine()) // 最大5张图片、最大3个视频、最大1个音频
            .maxSelectablePerMediaType(
                null, 5, 3, 3, 0, 0, 0
            ).forResult(object : OnResultCallbackListener {
                override fun onResult(result: List<LocalFile>) {
                    var filePath = result?.get(0)?.path
                    if (!TextUtils.isEmpty(filePath)) {
                        var files = ArrayList<String>()
                        files.add(filePath!!)
                        uploadFiles(files, {
                            mSelectedImageView?.addMoreData(it)
                        })
                    }
                }

                override fun onResultFromPreview(result: List<MultiMedia>, apply: Boolean) {

                }
            })
    }

    /**
     * 跳转系统视频录制
     */
    private fun jumpSystemVideoRecord(mActivity: BaseActivity) {
        CameraActivity.start(mActivity, true, object : CameraActivity.OnCameraListener {
            override fun onSelected(file: File) {
                var videoBean = VideoSelectActivity.VideoBean.newInstance(file.path)
                var videoDuration = videoBean.getVideoDuration()
                var videoSize = videoBean.getVideoSize()
                //最大时常1分钟
                var maxDuration = 60 * 1000
                if (videoDuration > maxDuration) {
                    ToastUtils.show("视频录制不能超过60秒，请重新录制")
                    return
                }
                handlerSelectedVideoResult(videoBean.getVideoPath())
            }

            private fun handlerSelectedVideoResult(path: String) {
                var photos = ArrayList<String>()
                photos.add(path)
                uploadFiles(photos, {
                    mSelectedImageView?.addMoreData(it)
                })
            }

            override fun onError(details: String) {
                ToastUtils.show(details)
            }
        })
    }

    fun uploadFiles(files: ArrayList<String>?, callBack: (ArrayList<String>) -> Unit) {
        mActivity?.let { mActivity ->
            mActivity.showDialog()
            var localFilePaths = getUploadFilesBean(files)
            getVideoThumbnailList(localFilePaths, { videoThumbnailList ->
                //上传缩略图
                CommonUploadUtils.uploadFiles(mActivity,
                    videoThumbnailList,
                    { success, errorMsg, videoThumbnailList ->
                        if (success) {
                            //设置缩略题地址
                            for (index in 0..videoThumbnailList!!.size - 1) {
                                localFilePaths.get(index).videoThumbnailUrl = videoThumbnailList.get(index).url
                            }
                            //上传视频
                            CommonUploadUtils.uploadFiles(
                                mActivity, localFilePaths, { success, errorMsg, urls ->
                                    mActivity.hideDialog()
                                    if (success) {
                                        var retList = ArrayList<String>()
                                        urls?.forEach {
                                            uploadSuccessList.add(it)
                                            retList.add(it.videoThumbnailUrl)
                                        }
                                        callBack(retList)
                                    } else {
                                        ToastUtils.show(errorMsg)
                                    }
                                }, false
                            )
                        } else {
                            mActivity.hideDialog()
                            ToastUtils.show(errorMsg)
                        }
                    })
            })
        }
    }

    private fun getUploadFilesBean(files: ArrayList<String>?): List<CommonFileBean> {
        var list = ArrayList<CommonFileBean>()
        files?.forEach {
            list.add(CommonFileBean(it))
        }
        return list
    }

    /**
     * 获取缩略图
     */
    fun getVideoThumbnailList(
        localFilePaths: List<CommonFileBean>, callBack: (List<CommonFileBean>) -> Unit
    ) {
        Observable.create<ArrayList<CommonFileBean>> {
            var videoThumbnailList = ArrayList<CommonFileBean>()
            localFilePaths.forEach {
                if (!TextUtils.isEmpty(it.videoThumbnailUrl)) {
                    videoThumbnailList.add(CommonFileBean(it.videoThumbnailUrl))
                } else {
                    var videoThumbnailUrl =
                        VideoThumbnailUtil.getVideoThumbnail(mActivity!!, it.url)
                    if (videoThumbnailUrl != null) {
                        videoThumbnailList.add(CommonFileBean(videoThumbnailUrl))
                    } else {
                        mActivity?.post({
                            mActivity?.hideDialog()
                            ToastUtils.show("获取视频缩略图失败")
                        })
                        return@create
                    }
                }
            }
            it.onNext(videoThumbnailList)
        }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe {
            callBack(it)
        }
    }
}